package statisticabusiness.grafica;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import statisticabusiness.engine.*;

/**
 * Questa classe crea avvia l'applicazione e la grafica.
 * @author Gagliano Turi, Giuffrida Alberto
 */
public class Interfaccia extends javax.swing.JFrame {

    /**
     * Creates new form Interfaccia
     */
    public Interfaccia() {
        nomiColonne=new String[]{""};
        initComponents();
        this.setLocationRelativeTo(null);
        aggiornaValoriEtichette();
        jBTNAvvia.setEnabled(false);
        jBTNAvviaNonG.setEnabled(false);
        jTabbedPane1.setEnabledAt(1, false);
        jTabbedPane1.setEnabledAt(2, false);
        jTabbedPane1.setEnabledAt(3, false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jTFNumeroVariabili = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jCBAlgoritmo = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jTFMinkowski = new javax.swing.JTextField();
        jBTNAvvia = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTable3 = new javax.swing.JTable();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTFNumeroGruppiFinali = new javax.swing.JTextField();
        jBTNAvviaNonG = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jBAggiungi = new javax.swing.JButton();
        jBRimuovi = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTAReport = new javax.swing.JTextArea();
        jBTNSalvaTXT = new javax.swing.JButton();
        jBTNDisegnaDendr = new javax.swing.JButton();

        jFileChooser1.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
        jFileChooser1.setDialogTitle("Salva resoconto su file");
        jFileChooser1.setFileFilter(new FileNameExtensionFilter("File TXT", "txt"));

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Tesina di SPB di Gagliano-Giuffrida");

        jTabbedPane1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jTabbedPane1StateChanged(evt);
            }
        });

        jTFNumeroVariabili.setText("1");
        jTFNumeroVariabili.setInputVerifier(new ControlloMaggioreUnoIntero());
        jTFNumeroVariabili.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTFNumeroVariabiliActionPerformed(evt);
            }
        });

        jLabel1.setText("Numero di variabili:");

        jLabel3.setText("Metodo gerarchico scelto:");

        jCBAlgoritmo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Legame Singolo", "Legame Completo", "McQuitty", "Legame Medio", "Centroide" }));

        jLabel4.setText("Coefficente di Minkowski:");

        jTFMinkowski.setText("1");
        jTFMinkowski.setInputVerifier(new ControlloMaggioreUno());

        jBTNAvvia.setText("Avvia");
        jBTNAvvia.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBTNAvviaActionPerformed(evt);
            }
        });

        jTable3.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Numero di gruppi", "Distanza al momento dell'unione"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane3.setViewportView(jTable3);

        jLabel5.setFont(new java.awt.Font("DejaVu Sans", 0, 24)); // NOI18N
        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel5.setText("Algoritmi Gerarchici");

        jLabel6.setFont(new java.awt.Font("DejaVu Sans", 0, 24)); // NOI18N
        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel6.setText("Algoritmi Non Gerarchici");

        jLabel2.setText("Numero di gruppi finali:");

        jTFNumeroGruppiFinali.setText("1");
        jTFNumeroGruppiFinali.setInputVerifier(new ControlloMaggioreUnoIntero());

        jBTNAvviaNonG.setText("Avvia");
        jBTNAvviaNonG.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBTNAvviaNonGActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jBTNAvvia, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(jLabel1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jTFNumeroVariabili, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(jLabel3)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jCBAlgoritmo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(jLabel4)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jTFMinkowski))
                                .addComponent(jSeparator1)
                                .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                    .addComponent(jLabel2)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jTFNumeroGruppiFinali, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(jBTNAvviaNonG, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 322, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 446, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(16, 16, 16)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(jTFNumeroVariabili, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jCBAlgoritmo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jTFMinkowski, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(jBTNAvvia, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jTFNumeroGruppiFinali, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(jBTNAvviaNonG, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        jTabbedPane1.addTab("Base", jPanel1);

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Variabili"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable2.getTableHeader().setResizingAllowed(false);
        jTable2.getTableHeader().setReorderingAllowed(false);
        jScrollPane2.setViewportView(jTable2);
        jTable2.getColumnModel().getColumn(0).setResizable(false);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 814, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 566, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("Etichette", jPanel3);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jBAggiungi.setText("Aggiungi riga");
        jBAggiungi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBAggiungiActionPerformed(evt);
            }
        });

        jBRimuovi.setText("Rimuovi riga");
        jBRimuovi.setToolTipText("");
        jBRimuovi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBRimuoviActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 814, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jBAggiungi, javax.swing.GroupLayout.PREFERRED_SIZE, 413, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBRimuovi, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 521, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBAggiungi, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jBRimuovi))
                .addContainerGap())
        );

        jTabbedPane1.addTab("Dati", jPanel2);

        jTAReport.setColumns(20);
        jTAReport.setEditable(false);
        jTAReport.setRows(5);
        jScrollPane4.setViewportView(jTAReport);

        jBTNSalvaTXT.setText("Salva come file TXT");
        jBTNSalvaTXT.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBTNSalvaTXTActionPerformed(evt);
            }
        });

        jBTNDisegnaDendr.setText("Disegna Dendrogramma");
        jBTNDisegnaDendr.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBTNDisegnaDendrActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 814, Short.MAX_VALUE)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(jBTNSalvaTXT, javax.swing.GroupLayout.PREFERRED_SIZE, 399, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBTNDisegnaDendr, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 512, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jBTNSalvaTXT, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
                    .addComponent(jBTNDisegnaDendr, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        jTabbedPane1.addTab("Resoconto", jPanel4);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 12, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTabbedPane1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jTabbedPane1StateChanged
        if (jTabbedPane1.getSelectedIndex()==1) { //Se sto entrando nella tab dell'etichette
                aggiornaValoriEtichette(); //Aggiorna i valori nella tab "Etichette"
                jTabbedPane1.setEnabledAt(2, true); //e attiva il tab "Dati"
        } else {
            salvaValoriEtichette(); //Salva i valori delle etichette
        }
        if (jTabbedPane1.getSelectedIndex()==2) { //Se sto entrando nella tab dei dati
            aggiornaValoriEtichette2(); //Aggiorna i nomi delle colonne
        } else {
            salvaValori(); //Salva i dati in memoria
        }
    }//GEN-LAST:event_jTabbedPane1StateChanged

    /**
     * Salva i valori nella tabella Etichette nell'array "nomiColonne"
     */
    private void salvaValoriEtichette() {
        DefaultTableModel DT = (DefaultTableModel) jTable2.getModel(); //prende il modello
        int limite = DT.getRowCount(); //per il numero di righe
        for (int i=0; i<limite; i++) {
            nomiColonne[i]=(String)DT.getValueAt(i, 0); //salva il valore
        }
    }
    
    /**
     * Salva i valori dalla tabella nella tab "Dati" nell'ArrayList dati
     */
    private void salvaValori() {
        DefaultTableModel DT = (DefaultTableModel) jTable1.getModel();
        dati = new ArrayList<int[]>();
        for (int i = 0; i<DT.getRowCount();i++) { //Per ogni riga
            int[] rigavalori = new int[DT.getColumnCount()]; 
            for (int j = 0; j<DT.getColumnCount();j++) //Per ogni colonna
                try {
                    rigavalori[j] = Integer.parseInt((String)DT.getValueAt(i, j));
                } catch (Exception e) {
                    rigavalori[j] = 0;
                }
            dati.add(rigavalori);
        }
    }
    
    /**
     * Cambiando il numero delle variabili nella prima tab, aggiorna la tabella etichette, creando nuove celle vuote e ricopiando i vecchi valori, oppure cancella i valori in eccesso. 
     */
    private void jTFNumeroVariabiliActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTFNumeroVariabiliActionPerformed
        String[] nomiColonneTemp=new String[Integer.parseInt(jTFNumeroVariabili.getText())];
        int dimensioni = nomiColonneTemp.length;
        if (nomiColonne.length<nomiColonneTemp.length) dimensioni=nomiColonne.length;
        for (int i=0; i<dimensioni; i++) {
            nomiColonneTemp[i]=nomiColonne[i];
        }
        nomiColonne=nomiColonneTemp;
        jTabbedPane1.setEnabledAt(1, true);
        jTabbedPane1.setEnabledAt(2, false);
    }//GEN-LAST:event_jTFNumeroVariabiliActionPerformed

    /**
     * Crea una nuova riga, aggiungendo un vettore di zeri. 
     */
    private void jBAggiungiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBAggiungiActionPerformed
        jBTNAvvia.setEnabled(true);
        DefaultTableModel DT = (DefaultTableModel) jTable1.getModel();
        Object[] vuoti = new Object[DT.getColumnCount()];
        for (int i=0;i<DT.getColumnCount();i++) {
            vuoti[i]=new Integer(0);
        }
        DT.addRow(vuoti);
    }//GEN-LAST:event_jBAggiungiActionPerformed

    /**
     * Rimuove la riga selezionata. 
     */
    private void jBRimuoviActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBRimuoviActionPerformed
        DefaultTableModel DT = (DefaultTableModel) jTable1.getModel();
        if (jTable1.getSelectedRow()!=-1) DT.removeRow(jTable1.getSelectedRow());
    }//GEN-LAST:event_jBRimuoviActionPerformed

    /**
     * Avvia algoritmi gerarchirci 
     */
    private void jBTNAvviaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBTNAvviaActionPerformed
        cont=0;  //questo va bene
        numVar = Integer.parseInt(jTFNumeroVariabili.getText());
        coeffMin = Double.parseDouble(jTFMinkowski.getText());
        matriciSequenziali= new ArrayList<double[][]>(); //lista matrici ottenute dopo ogni step
        unioni= new ArrayList<int[]>();   //usata in centroide e legame medio
        dendr = new ArrayList<int[]>(); 
        vd = new HashMap<Integer,Double>();
        
        
        //Calcola la Distanz di Minkowski
        DistMinkowski dm = new DistMinkowski(coeffMin, numVar, matriciSequenziali, dati);
        dm.distanzaMinkowski();
        
        //A seconda della selezione, attiva l'algoritmo scelto.
        
        if (jCBAlgoritmo.getSelectedIndex()==0) { //Legame Singolo
            LegameSingolo lg=new LegameSingolo(cont, matriciSequenziali,dendr, vd);
            lg.legameSingolo();
        }
        
        if (jCBAlgoritmo.getSelectedIndex()==1) { //Legame Completo
            LegameCompleto lc=new LegameCompleto(cont, matriciSequenziali,dendr,vd);
            lc.legameCompleto();
        }
        
        if (jCBAlgoritmo.getSelectedIndex()==2) { //McQuitty
        
            McQuitty mq=new McQuitty(cont, matriciSequenziali,dendr,vd);
            mq.mcQuitty();
        }
        
        if (jCBAlgoritmo.getSelectedIndex()==3) { //Legame Medio
        
            LegameMedio lm=new LegameMedio(cont, matriciSequenziali, unioni,dendr,vd);
            lm.legameMedio();
        }
        
        if (jCBAlgoritmo.getSelectedIndex()==4) { //Centroide
        
            Centroide cent =new Centroide(cont, matriciSequenziali, unioni,dendr,vd);
            cent.centroide();
        }
        
        //Riempie la tabella delle distanze.
        DefaultTableModel DT = (DefaultTableModel) jTable3.getModel();
        DT.setRowCount(0);
        Iterator itr = vd.keySet().iterator();
        while (itr.hasNext()) {
            Object valori[] = new Object[2];
            valori[0] = (Integer) itr.next();
            valori[1] = (Double) vd.get(valori[0]);
            DT.addRow(valori);
        }
        
        jBTNAvviaNonG.setEnabled(true); //Attiva il tasto per i non gerarchici
        jTabbedPane1.setEnabledAt(3, true); //Attiva il tab dei Resoconti.
        stampa(); //E lo stampa.
    }//GEN-LAST:event_jBTNAvviaActionPerformed

    /**
     * Attiva i non gerarchici 
     */
    private void jBTNAvviaNonGActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBTNAvviaNonGActionPerformed
        gruppi = new ArrayList<LinkedList<int[]>>(Integer.parseInt(jTFNumeroGruppiFinali.getText()));
        Kmeans KM = new Kmeans(dati,Integer.parseInt(jTFNumeroGruppiFinali.getText()),numVar,coeffMin,gruppi);
        KM.kmeans(); //Calcola
        stampaKmeans(); //e stampa
    }//GEN-LAST:event_jBTNAvviaNonGActionPerformed

    /**
     * Salva come TXT il resoconto.
     */
    private void jBTNSalvaTXTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBTNSalvaTXTActionPerformed
        int returnVal = jFileChooser1.showSaveDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = jFileChooser1.getSelectedFile();
            String filePath = file.getPath();
            if(!filePath.toLowerCase().endsWith(".txt"))
            {
                file = new File(filePath + ".txt");
            }
            try {
                PrintStream output = new PrintStream(new FileOutputStream(file));
                output.print(jTAReport.getText());
            } catch (IOException ex) {
                System.out.println("Problema accesso file"+file.getAbsolutePath());
            }
        } else {
            System.out.println("Annullato dall'utente.");
        }
    }//GEN-LAST:event_jBTNSalvaTXTActionPerformed

    /**
     * Disegna il dendrogramma. 
     */
    private void jBTNDisegnaDendrActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBTNDisegnaDendrActionPerformed
        DisegnaDend dd=new DisegnaDend();
        dd.DisegnaDendogram(dendr);
    }//GEN-LAST:event_jBTNDisegnaDendrActionPerformed

    /**
     * Ricopia i valori da nomiColonne e li inserisce nella tabella per modificare le etichette.
     */
    private void aggiornaValoriEtichette(){
        DefaultTableModel DT = (DefaultTableModel) jTable2.getModel();
        int limite = DT.getRowCount();
        for (int i=0; i<limite; i++) {
            DT.removeRow(0);
        }
        for (int i=0; i<nomiColonne.length; i++) {
            DT.addRow(new String[]{nomiColonne[i]});
        }
    }
    
    /**
     * Nella tabella del tab "Dati" aggiorna le etichette delle colonne in base al valore di nomiColonne.
     */
    private void aggiornaValoriEtichette2(){
        DefaultTableModel DT = (DefaultTableModel) jTable1.getModel();
        DT.setColumnIdentifiers(nomiColonne);
    }
    
    /**
     * Stampa i resoconti.
     */
    public void stampa(){
        int index=0;
        String m0="Le distanze di Minkowski ottenute sono rappresentate nella seguente matrice\n\n";
        String m1="Sequenza delle matrici delle distanze calcolate con l'algoritmo gerarchico: \t";
        DecimalFormat df = new DecimalFormat("########.#######");
        df.setMinimumFractionDigits(5);
        df.setMinimumIntegerDigits(8);
        df.setMaximumFractionDigits(5);
        df.setMaximumIntegerDigits(8);
        Iterator itr = matriciSequenziali.iterator();
        jTAReport.setText("Resoconto dei calcoli: \n\n\n");
        jTAReport.append(m0);
               
        double[][] distanze = (double[][])matriciSequenziali.get(0);
            for(int i=0; i<distanze.length; i++){
                for(int j=0; j<distanze.length; j++){   
                    jTAReport.append("[" + df.format(distanze[i][j]) + "]\t");
                }
                jTAReport.append("\n");
            }
            jTAReport.append("\n\n");
    
        jTAReport.append(m1+ (String)this.jCBAlgoritmo.getSelectedItem()+ "\n\n");
        
        while (itr.hasNext()) {
            double[][] d = (double[][]) itr.next();
            if(d.length==distanze.length) continue;
            jTAReport.append("L'elemento minore è in posizione:\t"+ String.valueOf(dendr.get(index)[0]) + ",\t"+String.valueOf(dendr.get(index)[1])+"\n");
            for(int i=0; i<d.length; i++){
                for(int j=0; j<d.length; j++){   
                    jTAReport.append("[" + df.format(d[i][j]) + "]\t");
                }
                jTAReport.append("\n");
            }
            jTAReport.append("\n\n");
        }
    }
    
    /**
     * Stampa i risultati degli algoritmi non gerarchici
     */
    public void stampaKmeans(){
        DecimalFormat df = new DecimalFormat("########.#######");
        df.setMinimumFractionDigits(5);
        df.setMinimumIntegerDigits(8);
        df.setMaximumFractionDigits(5);
        df.setMaximumIntegerDigits(8);
        String m2="Elenco dei gruppi ottenuti con l'algoritmo non gerarchico: \n\n";
        int[] app;
        jTAReport.append(m2);
        jTAReport.append("Sono stati creati " + jTFNumeroGruppiFinali.getText() + " gruppi.\n\n");
        for(int i=0; i<Integer.parseInt(jTFNumeroGruppiFinali.getText()); i++){
            jTAReport.append("Nel gruppo " + (i+1) + " sono presenti:\n");
            Iterator it= gruppi.get(i).iterator();
            while(it.hasNext()){
            
                app= (int[]) it.next();
                jTAReport.append("[");
                
                if(app==null) continue;
                jTAReport.append(df.format(app[0]));
                for(int w=1; w<app.length ;w++){
                    jTAReport.append("," + df.format(app[w]));
                }
                jTAReport.append("]\n");
            }
        }
        jTAReport.append("\n\nFine del processo.");
    }
    
    /**
     * Avvia il programma.
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Interfaccia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Interfaccia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Interfaccia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Interfaccia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        
        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Interfaccia().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBAggiungi;
    private javax.swing.JButton jBRimuovi;
    private javax.swing.JButton jBTNAvvia;
    private javax.swing.JButton jBTNAvviaNonG;
    private javax.swing.JButton jBTNDisegnaDendr;
    private javax.swing.JButton jBTNSalvaTXT;
    private javax.swing.JComboBox jCBAlgoritmo;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextArea jTAReport;
    private javax.swing.JTextField jTFMinkowski;
    private javax.swing.JTextField jTFNumeroGruppiFinali;
    private javax.swing.JTextField jTFNumeroVariabili;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTable jTable3;
    // End of variables declaration//GEN-END:variables
    private String[] nomiColonne;
    private int numVar, cont;    
    double coeffMin;
    private ArrayList<int[]> dati,unioni,dendr;
    private ArrayList<double[][]> matriciSequenziali; //la prima e' quella delle distanze iniziali
    public HashMap<Integer,Double> vd;
    ArrayList<LinkedList<int[]>> gruppi;
}
